package com.wonders.service.impl;

import com.wonders.utils.RedisIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: TODO:测试RedisIdUtils
 * @Author: yyalin
 * @CreateDate: 2023/8/13 12:27
 * @Version: V1.0
 */
@Service
@Slf4j
public class TestRedisIdUtils {
    @Autowired
    private RedisIdUtils redisIdUtils;
    //使用自定义的线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(500);
    /**
     * 功能描述:使用多线程测试生成40000条数据耗时
     * @MethodName: testIdWorker
     * @MethodParam: [nums]
     * @Return: void
     * @Author: yyalin
     * @CreateDate: 2023/8/13 12:36
     */
    public void testIdWorker(int nums) throws InterruptedException {
        //同步协调在多线程的等待于唤醒问题 分线程全部走完之后，主线程再走
        CountDownLatch latch = new CountDownLatch(nums);
        Runnable task = () -> {
            for (int i = 0; i < 100; i++) {
                long id = redisIdUtils.nextId("order");
                System.out.println("id = " + id);
            }
            latch.countDown();
        };
        long begin = System.currentTimeMillis();
        for (int i = 0; i < nums; i++) {
            executorService.submit(task);
        }
        //阻塞方法 让main线程阻塞
        latch.await();
        long end = System.currentTimeMillis();
        log.info("生成"+nums*100+"条id共计耗时(毫秒) = " + (end - begin));
    }
}

